import {Component, OnInit, OnDestroy} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {DatePipe} from '@angular/common';
import {Router, ActivatedRoute} from '@angular/router';

import {LoveRecycManageService} from '../love-recyc-manage.service';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, debounceTime, map, switchMap} from 'rxjs/operators';

enum BRANDTYPE {
  '手机' = 1,
  '平板',
}

@Component({
  selector: 'app-love-series-config',
  templateUrl: './love-series-config.component.html',
  styleUrls: ['./love-series-config.component.scss'],
  providers: [DatePipe]
})
export class LoveSeriesConfigComponent implements OnInit, OnDestroy {
  BRANDTYPE = BRANDTYPE;
  routerParams: any = {};

  // 品牌options
  baradListForm: any = {
    isLoading: false,
    page: 1,
    pageSize: 15,
    total: 0
  };
  brandOptions: any = [];

  // 系列options
  seriesOptions: any = [];
  nzFilterOption = (): boolean => true;
  isSeriesLoading: boolean = false;
  searchChange$ = new BehaviorSubject('');

  // seach form
  seachParams: any = {
    brandId: '', // 品牌ID
    name: '', // 系列名称
    category: '', // 品类
    beginTime: '',
    endTime: ''
  };
  updateTimes: any = [];

  tableData: any = [];
  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };

  // modal
  validateForm!: FormGroup;
  isVisible: boolean = false;
  modalType: number = 0; // 0：新增，1：编辑
  modalItem: any = {};
  subModalLoding: boolean = false;
  uploadLoading: boolean = false;

  constructor(
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private services: LoveRecycManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    });
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required]],
      brandId: ['', [Validators.required]],
      category: ['', [Validators.required]],
    });

    this.getBrandOption();
    if (this.routerParams.brandId) {
      this.seachParams.brandId = Number(this.routerParams.brandId);
    }

    // 系列名称下拉 防抖
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        if (!value && !this.seachParams.brandId) {
          this.seriesOptions = [];
          return;
        }
        this.loadSeriesOptions(value);
      });

    this.loadTable();
  }

  ngOnDestroy(): void {
    this.searchChange$.unsubscribe();
  }

  // 查询品牌options
  async getBrandOption() {
    try {
      let params = {
        page: this.baradListForm.page,
        pageSize: 99999
      };
      this.baradListForm.isLoading = true;
      const res: any = await this.services.getRecycleBrandList(params);
      this.baradListForm.isLoading = false;

      if (res.code == 0) {
        const {records, total}: any = res.data || {};
        this.brandOptions = this.brandOptions.concat(records || []);
        this.baradListForm.total = total || 0;
      } else {
        this.message.error(res.message || '品牌列表获取失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 品牌more
  loadMore() {
    if (this.baradListForm.total == this.brandOptions.length) {
      return;
    }
    this.baradListForm.page += 1;
    this.getBrandOption();
  }

  /**
   * 系列名称下拉 options
   * ----------------------------------------------------------------
   */
  async loadSeriesOptions(seriesName?: string) {
    let params = {
      brandId: this.seachParams.brandId,
      name: seriesName || '',
      page: 1,
      pageSize: 1000000
    };
    this.seriesOptions = [];
    this.isSeriesLoading = true;
    const res: any = await this.services.getRecycleSeriesList(params);
    this.isSeriesLoading = false;

    if (res.code == 0) {
      const {records, total} = res.data || {};
      this.seriesOptions = records || [];
    } else {
      this.seriesOptions = [];
    }
  }

  seriesSearch(value: any) {
    this.searchChange$.next(value);
  }

  // 品牌change
  brandChange(val: any) {
    if (!val) {
      this.seachParams.name = '';
      this.seriesOptions = [];
      return;
    }
    this.loadSeriesOptions();
  }

  async loadTable() {
    try {
      let params: any = {
        ...this.seachParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      };
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getRecycleSeriesList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const {records, total} = res.data || {};
        this.tableData = records || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }
    this.updateTimes = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 删除
  async deleteItem(item: any) {
    try {
      let params = {
        id: item.id,
        status: 2, // 0-禁用 1-启用 2-删除
      };
      const res: any = await this.services.updateRecycleSeries(params);
      if (res.code == 0) {
        this.message.success('删除成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // modal submit
  submitForm(): void {
    if (this.validateForm.valid) {
      this.subFormInterface();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  async subFormInterface() {
    try {
      let params: any = {
        ...this.validateForm.value
      };
      let res: any = null;

      this.subModalLoding = true;
      if (this.modalType == 0) {
        res = await this.services.saveRecycleSeries(params);
      } else {
        params.id = this.modalItem.id;
        res = await this.services.updateRecycleSeries(params);
      }
      this.subModalLoding = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.validateForm.reset();
        this.isVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 更新时间change
  timeChange(result: Date[]) {
    this.seachParams.beginTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.seachParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  /**
   * 新增、编辑
   * @param num 0：新增，1：编辑
   * @param item
   */
  showModal(num: number, item?: any) {
    if (num == 1) {
      this.modalItem = item;
      this.validateForm.patchValue({
        name: item.name,
        brandId: item.brandId,
        category: item.category,
      });
    }
    this.modalType = num;
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
    this.validateForm.reset();
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
